package com.fingard.dsp.bank.directbank.cdcb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

/**
 * @author: liuxb
 * @create: 2020-01-02 11:50
 * @version: 1.0
 **/
public class CDCB01Transaction extends CDCB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";// 返回码
        String tmpRespInfo = "";// 返回信息
        // 写返回ATS的统一头部信息
        retAtsTrans.writeStart();

        try {

            // 发送银行报文  赋值通用参数
            CDCB01Header bankHeader = new CDCB01Header();
            bankHeader.serviceId = "CMACCDTL";
            //拼接请求报文头,报文体
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            writeCommonHeader(xmlTextWriter, bankHeader);
            xmlTextWriter.writeElementString("ACCNO", p_req7516.actNum);//帐号
            xmlTextWriter.writeElementString("CRYTYPE", convertCurToBank(p_req7516.actCur));//币种代码
            xmlTextWriter.writeElementString("STARTDATE", p_req7516.dateFrom);//查询开始日期
            xmlTextWriter.writeElementString("ENDDATE", p_req7516.dateTo);//查询结束日期
//                xmlTextWriter.writeElementString("STARTDATE", Format.Date8Format.format(tmpCalendarFrom.getTime()));//查询开始日期
//                xmlTextWriter.writeElementString("ENDDATE", Format.Date8Format.format(tmpClndrStepTo.getTime()));//查询结束日期
            xmlTextWriter.writeEndDocument();

            //发送请求报文
            String[] bankResult = sendToBank(xmlTextWriter.toXmlString());

//                //模拟银行返回
//                String s = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
//                        "<stream>\n" +
//                        "<RETCODE>AAAAAAA</RETCODE>\n" +
//                        "<RETMSG>状态描述</RETMSG>\n" +
//                        "<list name=\"resultList\">\n" +
//                        "<row>\n" +
//                        "\t<TRANDATE>2019-12-12</TRANDATE>\n" +
//                        "\t<TRANTIME>2019-12-12 12:23:23</TRANTIME>\n" +
//                        "\t<TRANAMT>200.33</TRANAMT>\n" +
//                        "\t<ACCBAL>300.44</ACCBAL>\n" +
//                        "\t<CDFLAG>D</CDFLAG>\n" +
//                        "<ACCNO>121212</ACCNO>\n" +
//                        "<ACCNAME>交易账户名称</ACCNAME>\n" +
//                        "\t<OTHERACCNO>232323</OTHERACCNO>\n" +
//                        "\t<OTHERACCNAME>对方账户名称</OTHERACCNAME>\n" +
//                        "\t<OTHERBRANCHNAME>对方账户开户行名称</OTHERBRANCHNAME>\n" +
//                        "\t<MEMO>摘要</MEMO>\n" +
//                        "\t<CRYTYPE>CNY</CRYTYPE>\n" +
//                        "\t<REFERENCE>1234</REFERENCE>\n" +
//                        "\t<TRANDESC>交易描述</TRANDESC>\n" +
//                        "<HOSTSEQNO>23455</HOSTSEQNO>\n" +
//                        "<PRINTCNT>打印次数</PRINTCNT>\n" +
//                        "<SOURCETYPE>交易渠道</SOURCETYPE>\n" +
//                        "</row>\n" +
//                        "</list>\n" +
//                        "</stream>\n";
//                String[] bankResult = new String[]{"", s};

            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String IBSReturnCode = tmpBkReader.getFirstText("/stream/RETCODE");// 响应码
                    String IBSReturnMsg = tmpBkReader.getFirstText("/stream/RETMSG");// 响应信息
                    if ("AAAAAAA".equals(IBSReturnCode)) {
                        tmpRespCode = IBSReturnCode;
                        tmpRespInfo = IBSReturnMsg;
                        while (tmpBkReader.read("/stream/list/row")) {
                            RetAtsTransDetail detail = new RetAtsTransDetail();// 创建返回给ats的详细明细对象
                            XElement readXElement = tmpBkReader.readedXElement;// 创建读取返回报文的对象

                            String dealDate = readXElement.getSingleTextNotNull("TRANDATE").trim();//交易日期
                            detail.tranDate = dealDate.substring(0, 4) + "-" + dealDate.substring(4, 6) + "-" + dealDate.substring(6, 8);
                            detail.valueDate = detail.tranDate;//格式yyyy-MM-dd
                            detail.tranTime = detail.tranDate + " " + readXElement.getSingleTextNotNull("TRANTIME").trim();//格式"yyyy-MM-dd HH:mm:ss"//交易时间
                            detail.tranAmt = readXElement.getSingleTextNotNull("TRANAMT").trim();//交易金额
                            detail.accBal = readXElement.getSingleTextNotNull("ACCBAL").trim();//交易后余额
                            detail.actNum = readXElement.getSingleTextNotNull("ACCNO").trim();//交易账号
//                                    detail.recAccName = readXElement.getSingleTextNotNull("ACCNAME").trim();//交易账户名称
                            detail.recAccNum = readXElement.getSingleTextNotNull("OTHERACCNO").trim();//对方账号
                            detail.recAccName = readXElement.getSingleTextNotNull("OTHERACCNAME").trim();//对方账户名称
//                                    detail.tranDate = readXElement.getSingleTextNotNull("OTHERBRANCHNAME").trim();//对方账户开户行名称
                            detail.usage = readXElement.getSingleTextNotNull("MEMO").trim();//摘要
                            detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("CRYTYPE").trim());//币种
                            detail.billNum = readXElement.getSingleTextNotNull("REFERENCE").trim();//交易参考号（与付款账户联合唯一）
                            detail.comment = readXElement.getSingleTextNotNull("TRANDESC").trim();//交易描述
                            detail.bnkSeqNo = readXElement.getSingleTextNotNull("HOSTSEQNO").trim();//主机流水号

                            String cdFlag = readXElement.getSingleTextNotNull("CDFLAG").trim();//C：贷（存）   D：借（取）
                            String tranAmt = detail.tranAmt;//发生额
                            if ("D".equals(cdFlag)) {
                                if (tranAmt.substring(0, 1).equals("-")) {
                                    detail.cdFlag = "2";
                                    detail.tranAmt = tranAmt.substring(1);
                                } else {
                                    detail.cdFlag = "1";
                                    detail.tranAmt = tranAmt;
                                }
                            } else if ("C".equals(cdFlag)) {
                                if (tranAmt.substring(0, 1).equals("-")) {
                                    detail.cdFlag = "1";
                                    detail.tranAmt = tranAmt.substring(1);
                                } else {
                                    detail.cdFlag = "2";
                                    detail.tranAmt = tranAmt;
                                }
                            }

                            detail.actArea = p_req7516.actArea;
                            detail.valueDate = detail.tranDate;
                            retAtsTrans.writeRetDetail(detail);
                        }
                    } else if (IBSReturnCode != null && "AAAAAAE".equals(IBSReturnCode)) {// 已提交银行处理，需稍后使用“交易状态查询”交易进行查询
                        retAtsTrans.writeRespCode("-1");
                        retAtsTrans.writeRespInfo("已提交银行处理，需稍后使用“交易状态查询”交易进行查询");
                    } else if (IBSReturnCode != null && "UNKNOWN".equals(IBSReturnCode)) {// 交易状态未知，使用“交易状态查询”交易进行查询
                        retAtsTrans.writeRespCode("-1");
                        retAtsTrans.writeRespInfo("交易状态未知，使用“交易状态查询”交易进行查询");
                    }
//                        else {
//                            retAtsTrans.writeRespCode("-1");
//                            retAtsTrans.writeRespInfo(IBSReturnMsg);
//                        }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = bankResult[1];
            }

        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespCode("0");
            retAtsTrans.writeRespInfo("交易为空");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
